<?php

function xCreateAccount()
{
    global $data;
    
    $name = Trim($_POST["name"]);
    $pass = Trim($_POST["password"]);
    $pass2 = Trim($_POST["password2"]);
    $mail = Trim($_POST["mail"]);
    $sex = $_POST["sex"];
    $agree = (isset($_POST["agree"]) ? true : false);
    
    $ok = true;
    $msg = array();
    
    // ---------------------------
    // JMÉNO
    if ($name == "")
    {
        $ok = false;
        $msg[] = dl_lang_general("msg.empty_name");
    }
    
    $s = dibi::query("SELECT COUNT(*) FROM account WHERE name LIKE %s", $name);
    $kontrola = $s->fetchSingle();
    
    if ($kontrola > 0)
    {
        $ok = false;
        $msg[] = dl_lang_general("msg.used_name");
    }
    
    // ---------------------------
    // HESLO
    if ($pass == "" OR $pass2 == "" OR $pass != $pass2)
    {
        $ok = false;
        $msg[] = dl_lang_general("msg.password");
    }
    
    // ---------------------------
    // E-MAIL
    if (!check_email($mail))
    {
        $ok = false;
        $msg[] = dl_lang_general("msg.fail_mail");
    }
    
    // zabrání mailu
    $s = dibi::query("SELECT COUNT(*) FROM account WHERE mail LIKE %s", $mail);
    $kontrola = $s->fetchSingle();
    
    if ($kontrola > 0)
    {
        $ok = false;
        $msg[] = dl_lang_general("msg.used_mail");
    }
    
    // ---------------------------
    // PODMÍNKY
    if (!$agree)
    {
        $ok = false;
        $msg[] = dl_lang_general("msg.agreement");
    }
    
    // ---------------------------
    // KONTROLA
    
    if (!$ok)
    {
        $data["msg-error"] = implode("<br />", $msg);
        $data["formCreateAccount"] = $_POST;
        redirect("createAccount");
    }
    else
    {
        // ----- vše v pořádku
        $salt = random_string();
        $h = crypt::hmac_hash($pass, $salt);
        
        $insert = array("name"     => $name,
                        "password" => $h,
                        "salt"     => $salt,
                        "mail"     => $mail,
                        "pohlavi"  => $sex,
                        "created"  => Time(),
                        "avatar"   => "",
                        "tears"    => 5);
        dibi::query("INSERT INTO account", $insert);
        $data["msg-done"] = dl_lang_general("msg.account_created");
        unset($data["formCreateAccount"]);
        redirect("createAccount");
    }
}

function xLogin()
{
    global $data;
    
    $mail = Trim($_POST["mail"]);
    $pass = $_POST["password"];
    
    $ok = true;
    $msg = array();
    
    if ($mail == "" OR $pass == "")
    {
        $ok = false;
    }
 
    //existuje user?
    $s = dibi::query("SELECT id, salt FROM account WHERE mail = %s", $mail);
    $r = $s->fetchAll();

    if (count($r) == 1)
    {
        //sedí heslo?
        $heslo_hash = crypt::hmac_hash($pass, $r[0]->salt);
    }
    else
    {
        $heslo_hash = "";
    }
    
    $id = $r[0]->id;
    
    $s = dibi::query("SELECT name FROM account WHERE %and", array(array("mail     = %s", $mail),
                                                                  array("password = %s", $heslo_hash)));
    $r = $s->fetchAll();
    
    if (count($r) == 1 && $ok)
    {
          $nick = $r[0]->name;
          $data["user"]["id"]    = $id;
          $data["user"]["name"]  = $nick;
          
          //setAccountActual();
          writeToAccountLog($id, "Přihlášení k účtu", "IP: " . $_SERVER["REMOTE_ADDR"]);
          redirect("");          
    }
    else
    {
          $ok = false;
          
          if ($id != "")
          {
                writeToAccountLog($id, "Přihlášení k účtu", "neplatný e-mail.<br />IP: " . $_SERVER["REMOTE_ADDR"], 1);
          }
    }

    if (!$ok)
    {
          $msg[] = dl_lang_general("msg.fail_login");
          $data["formLogin"] = $_POST;
          $data["msg-login-error"] = implode("<br />", $msg);
          redirect("");
    }
    
}

function xlogout()
{
    global $data;
    
    dibi::query("UPDATE account SET online = '0' WHERE id = %i", $data["user"]["id"]);
    
    writeToAccountLog($data["user"]["id"], "Odhlášení", "IP: " . $_SERVER["REMOTE_ADDR"]);
    unset($data["user"]);
    unset($data["hero"]);
    redirect(""); 
}

function xsendMessage()
{
    global $data;
    
    $nick = Trim($_POST["account"]);
    $title = Trim($_POST["title"]);
    $text = Trim($_POST["text"]);
    
    $msg = array();
    $ok = true;
    
    // ---------- kontrola nicků
    if ($nick == "")
    {
        $msg[] = dl_lang_general("msg.messages_to1");
        $ok = false;
    }
    
    $s = dibi::query("SELECT id FROM account WHERE name LIKE %s", $nick);
    $id = $s->fetchSingle();
    
    if ($nick != "" && $id == "")
    {
        $msg[] = dl_lang_general("msg.messages_to2");
        $ok = false;
    }
    
    // ----------- kontrola textu
    if ($text == "")
    {
        $msg[] = dl_lang_general("msg.messages_body");
        $ok = false;
    }
    
    if (!$ok)
    {
        $data["msg-error"] = implode("<br />", $msg);
        $data["formMessage"] = $_POST;
        redirect("messages/new");
    }
    else
    {
        sendMessage($data["user"]["id"], $id, $title, $text);
        $data["msg-done"] = dl_lang_general("msg.messages_send");
        unset($data["formMessage"]);
        redirect("messages");
    } 
}

function xdeleteMessage()
{
    global $data;
    
    if (isset($_GET["arg1"]) && $_GET["arg1"] == "all")
    {
        dibi::query("DELETE FROM account_messages WHERE mess_to = %i", $data["user"]["id"]);
    }
    else if (isset($_GET["arg1"]) && is_numeric($_GET["arg1"]))
    {
        $s = dibi::query("SELECT COUNT(*) FROM account_messages WHERE id = %i", $_GET["arg1"], "AND mess_to = %i", $data["user"]["id"]);
        $kontrola = $s->fetchSingle();
        if ($kontrola > 0)
        {
            dibi::query("DELETE FROM account_messages WHERE id = %i", $_GET["arg1"]);   
        }
        else
        {
            $data["msg-error"] = dl_lang_general("msg.data_manipulation");
            redirect("messages");
        }
    }
    else
    {
        $in = "";
        foreach ($_POST["messages"] AS $mess)
        {
            $in .= ($in != "" ? "," : "") . "'$mess'";
        }
        dibi::query("DELETE FROM account_messages WHERE id IN ($mess) AND mess_to = %i", $data["user"]["id"]);
    }
    
    $data["msg-done"] = dl_lang_general("msg.messages_delete_done");
    redirect("messages");
    
}

function xCreateHero()
{
    global $data;
    
    $name = Trim($_POST["name"]);
    $race = $_POST["race"];
    $sex = $_POST["sex"];
    $agree = $_POST["agree"];
    
    $ok = true;
    $msg = array();
    $soubor = false;
    
    // ---------------------------
    // JMÉNO
    if ($name == "")
    {
        $ok = false;
        $msg[] = dl_lang_general("msg.empty_name");
    }
    
    $s = dibi::query("SELECT COUNT(*) FROM hero WHERE name LIKE %s", $name);
    $kontrola = $s->fetchSingle();
    
    if ($kontrola > 0)
    {
        $ok = false;
        $msg[] = dl_lang_general("msg.used_name");
    }
    
    // ---------------------------
    // AVATAR
    if ($_FILES["avatar"]["error"] == 0)
    {
        $e = explode(".", $_FILES["avatar"]["name"]);
        $type = end($e);

        if ($type != "jpg" && $type != "jpeg" && $type != "JPG" && $type != "JPEG" && $type != "gif" && $type != "png")
        { 
            $ok = false;
            $msg[] = dl_lang_general("msg.avatar_type");  
        } 
        else
        {
            $soubor = true;
        }           
    }

    
    // ---------------------------
    // PODMÍNKY
    if (!$agree)
    {
        $ok = false;
        $msg[] = dl_lang_general("msg.agreement");  
    }
    
    // ---------------------------
    // KONTROLA
    
    if (!$ok)
    {
        $data["msg-error"] = implode("<br />", $msg);
        $data["formCreateHero"] = $_POST;
        redirect("heroes/new");
    }
    else
    {
        // ----- příprava hodnot
        $insert = array("name"       => $name,
                        "account"    => $data["user"]["id"],
                        "race"       => $race,
                        "pohlavi"    => $sex,
                        "gold"       => 50,
                        "exp"        => 0,
                        "level"      => 1,
                        "created"    => Time());  
        
        $insert["strength"] = 1;
        $insert["dexterity"] = 1;
        $insert["intelligence"] = 1;
        $insert["vitality"] = 5;
        $insert["wisdom"] = 5;
        $insert["hp"] = 0;
        $insert["mana"] = 0; 
       
        // ----- insertování        
        dibi::query("INSERT INTO hero", $insert);
        $id = mysql_insert_id();
        
        // --------- příprava avataru
        if ($soubor == true)
        {
            move_uploaded_file($_FILES["avatar"]["tmp_name"], "images/tmp/avatar" . $id . "." . $type);

            switch (strtolower($type))
            {
                case "jpeg":
                case "jpg": $fce = "imagecreatefromjpeg"; break;
                case "png": $fce = "imagecreatefrompng"; break;
                case "gif": $fce = "imagecreatefromgif"; break;
                default: $fce = "";
            }
            
            $img = $fce("images/tmp/avatar" . $id . "." . $type);

            $avatar = imagecreatetruecolor(150, 200);
            imagecopyresized($avatar, $img, 0, 0, 0, 0, 150, 200, imagesx($img), imagesy($img));
            imagejpeg($avatar, "images/avatar/avatar" . $id . "." . $type, 100);

            imagedestroy($img);

            unlink("images/tmp/avatar" . $id . "." . $type);
            
            dibi::query("UPDATE hero SET avatar = %s", "avatar".$id.".".$type, "WHERE id = %i", $id);   
        }    
        
        $data["msg-done"] = dl_lang_general("msg.hero_created");
        unset($data["formCreateHero"]);
        redirect("heroes");
    }
}